import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/observable';
// import 'rxjs/add/operator/map';
// import 'rxjs/add/observable/of';
// import 'rxjs/add/operator/filter';
// import 'rxjs/add/operator/mergeMap';
// tslint:disable
import 'rxjs/Rx';

@Injectable()
export class WebscoketService {
  ws: WebSocket;
  ws2: WebSocket;

  constructor() { }

  createObservableSocket(url: string): Observable<any> {
    console.log('createObservableSocket url: ', url); //  ws://localhost:8086
    this.ws = new WebSocket(url);
    return new Observable(
      observer => {
        this.ws.onmessage = (event) => observer.next(event.data);
        // 异常处理
        this.ws.onerror = (event) => observer.error(event);
        // 流结束啦
        this.ws.onclose = (event) => observer.complete();
      }
    );
  }

  sendMessage(message: string) {
    this.ws.send(message);
  }

  createObservableSocket2(url: string, id: number): Observable<any> {
    console.log('createObservableSocket url: ', url); //  ws://localhost:8087
    this.ws2 = new WebSocket(url);
    let tempObservable = new Observable<string>(
      observer => {
        this.ws2.onmessage = (event) => observer.next(event.data);
        // 异常处理
        this.ws2.onerror = (event) => observer.error(event);
        // 流结束啦
        this.ws2.onclose = (event) => observer.complete();
        // 
        this.ws2.onopen = (event) => this.sendMessage2({ productId: id });
        // 关闭数据流
        return () => this.ws2.close();
      }
    )
    console.log('tempObservable: ', tempObservable);
    return tempObservable;
    // return tempObservable.map(message => { JSON.parse(message) });
  }

  sendMessage2(message: any) {
    // console.log('sendMessage2() 执行:', message);
    this.ws2.send(JSON.stringify(message));
  }

}
